import java.io.*;
import java.util.Random;
import java.util.Scanner;

public class Main {
    private static final int NUM_ACCOUNTS = 20;
    private static final int INITIAL_BALANCE = 1000;
    private static final int NUM_TRANSACTIONS = 100;
    private static final String TRANSACTION_FILE = "transactions.txt";

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入线程数量：");
        int numWorkers = scanner.nextInt();
        scanner.close();

        // 生成交易文件
        generateTransactionFile();

        // 初始化银行和账户
        Bank bank = new Bank(NUM_ACCOUNTS, INITIAL_BALANCE, numWorkers);
        bank.startWorkers();

        // 从文件读取交易
        try (BufferedReader reader = new BufferedReader(new FileReader(TRANSACTION_FILE))) {
            String line;
            while ((line = reader.readLine()) != null) {
                Transaction transaction = Transaction.parse(line);
                if (transaction != null) {
                    bank.addTransaction(transaction);
                }
            }
            // 添加毒丸表示交易结束
            bank.addTransaction(Transaction.getPoisonPill());
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 等待所有交易完成
        try {
            bank.waitForCompletion();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 打印结果
        bank.printAccountBalances();
    }

    private static void generateTransactionFile() {
        Random random = new Random();
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(TRANSACTION_FILE))) {
            for (int i = 0; i < NUM_TRANSACTIONS; i++) {
                int fromAccount = random.nextInt(NUM_ACCOUNTS) + 1; // 1-20
                int toAccount;
                do {
                    toAccount = random.nextInt(NUM_ACCOUNTS) + 1;
                } while (toAccount == fromAccount); // 确保不向自己转账

                int amount = random.nextInt(500) + 1; // 1-500的随机金额
                writer.write(fromAccount + " " + toAccount + " " + amount);
                writer.newLine();
            }
            System.out.println("已生成 " + NUM_TRANSACTIONS + " 条交易记录到 " + TRANSACTION_FILE);
        } catch (IOException e) {
            System.err.println("生成交易文件失败: " + e.getMessage());
        }
    }
}